package com.sell.controller;

import com.sell.common.HttpResult;
import com.sell.dataobject.ProductCategory;
import com.sell.dataobject.ProductInfo;
import com.sell.service.CategoryService;
import com.sell.service.ProductInfoService;
import com.sell.vo.ProductInfoVo;
import com.sell.vo.ProductVo;
import com.sell.vo.ResultVo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 买家商品
 * Created by megan on 2018/2/10.
 */
@RestController
@RequestMapping("/buyer/product")
public class BuyerProductController {

    @Autowired
    private ProductInfoService productInfoService;

    @Autowired
    private CategoryService categoryService;

    @GetMapping("/list")
    public ResultVo list(){
        // 1, 查询所有上架的商品
        List<ProductInfo> productInfoList = productInfoService.findUpAll();
        // 2，查询类目（一次性查询）精简做法（java 8 lambada表达试）
        /* List<Integer> categoryTypeList = new ArrayList<>();
        for(ProductInfo info : productInfoList){
            categoryTypeList.add(info.getCategoryType());
        }*/
        List<Integer> categoryTypeList = productInfoList.stream()
                .map(e -> e.getCategoryType()).collect(Collectors.toList());
        List<ProductCategory> productCategories = categoryService.findByCategoryTypeIn(categoryTypeList);
        // 3，数据拼装
        List<ProductVo> productVoList = new ArrayList<>();
        for (ProductCategory category : productCategories) {
            ProductVo peoVo = new ProductVo();
            peoVo.setCategoryType(category.getCategoryType());
            peoVo.setCategoryName(category.getCategoryName());
            List<ProductInfoVo> productInfoVoList = new ArrayList<>();
            for(ProductInfo info : productInfoList){
                if(info.getCategoryType().equals(category.getCategoryType())){
                    ProductInfoVo infoVo = new ProductInfoVo();
                    BeanUtils.copyProperties(info,infoVo);
                    productInfoVoList.add(infoVo);
                }
            }
            productVoList.add(peoVo);
            peoVo.setProductInfoVoList(productInfoVoList);
        }
        return HttpResult.success(productVoList);
    }
}
